package com.solocredit.finance.ui.main.fm

import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.adapter.MullaOnItemChildClickListener
import com.solocredit.finance.databinding.FmMullaRepayBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.MvpFm
import com.solocredit.finance.ui.loan.act.MullaLoanRepayAct
import com.solocredit.finance.ui.main.adapter.MullaRepayAdapter
import com.solocredit.finance.ui.main.impl.MullaRepayPresenterImpl
import com.solocredit.finance.ui.main.view.IMullaRepayView
import com.solocredit.finance.ui.user.act.MullaUserLuckyDrawAct
import com.solocredit.finance.ui.user.act.MullaUserMessageAct
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 16:57
 * @Annotation：待还款
 */
class MullaRepayFm: MvpFm<IMullaRepayView, MullaRepayPresenterImpl>(),IMullaRepayView {
    private var _binding: FmMullaRepayBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    //待还款列表
    private var repayAdapter: MullaRepayAdapter? = null

    override fun createPresenter(): MullaRepayPresenterImpl {
        return MullaRepayPresenterImpl(context)
    }

    override fun getMullaRootView(inflater: LayoutInflater): View {
        _binding = FmMullaRepayBinding.inflate(inflater)
        return binding.root
    }

    override fun initMullaView() {
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setMullaBackBtnRes(R.mipmap.mulla_kefu_dialog_icon)
        setMullaRightBtnRes(R.mipmap.mulla_message_icon)
        setMullaTextTitle(getString(R.string.loan_repayment_title))
        isInterceptBack(true)
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#FFFFFFFF"))

        initMullaRefreshLayout()
        initMullaRecyclerView()

        val showTipsKey = getString(R.string.loan_credit_score_result)
        val showTipsText = String.format(getString(R.string.loan_credit_score_tips),showTipsKey)
        val spString = SpannableString(showTipsText)
        val start = showTipsText.indexOf(showTipsKey)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFFAC25")), start, showTipsText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textScoreTips?.text = spString

        val showText = String.format(getString(R.string.loan_repayment_empty),getString(R.string.loan_repayment_apply))
        val startIndex = showText.indexOf(getString(R.string.loan_repayment_apply))
        val emptySpannableString = SpannableString(showText)
        emptySpannableString.setSpan(ForegroundColorSpan(Color.parseColor("#FFD21034")), startIndex, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        emptySpannableString.setSpan(UnderlineSpan(), startIndex, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textEmpty?.text = emptySpannableString
    }

    override fun initMullaListener() {
        rootViewBinding.ivBaseBack.setOnClickListener {
            showMullaKefuDialog("Repayment Page")
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"Repayment Page")
        }
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(MullaUserMessageAct::class.java)
        }
        //抽奖
        _binding?.giftLayout?.setOnClickListener {
            onIntent(MullaUserLuckyDrawAct::class.java)
        }
        // Apply Now 、 Repay Now
        _binding?.textEmpty?.setOnClickListener {
            MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_SHOW_PRODUCTS))
            MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_SHOW_HOME))
        }
    }

    override fun initMullaData() {
        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.visibility = View.GONE
        } else {
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.addView(licenseView())
            _binding?.licenseLayout?.visibility = View.VISIBLE
        }
        presenter.loadMullaRepayListAction()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LOAN_REPAY_START)
    }

    /* 初始化刷新 */
    private fun initMullaRefreshLayout() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_PRODUCT_REFRESH))
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    /**
     * 初始化产品列表
     */
    private fun initMullaRecyclerView() {
        _binding?.recyclerView?.layoutManager = LinearLayoutManager(context)
        repayAdapter = MullaRepayAdapter(_binding?.recyclerView)
        _binding?.recyclerView?.adapter = repayAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        repayAdapter?.setOnItemChildClickListener(MullaOnItemChildClickListener { _, childView, position ->
            repayAdapter?.let {
                val item = it.getItem(position)
                when (childView.id) {
                    R.id.itemLayout -> {//点击Item
                    }

                    R.id.detailsLayout -> {//查看详情
                        val pName = item.optString("product")
                        val pToken = item.optString("token")
                        MullaLoanRepayAct.start(requireContext(), pName, pToken)
                    }
                }
            }
        })
    }

    /**
     * 设置待还款列表
     */
    override fun showMullaRepayList(repayList: ArrayList<JSONObject>) {
        hideMullaLoading()
        if (isNewUser()){
            _binding?.scoreTipsLayout?.visibility = View.GONE
        } else {
            _binding?.scoreTipsLayout?.visibility = View.VISIBLE
        }
        repayList.let {
            if (it.size == 0){
                _binding?.recyclerView?.visibility = View.GONE
                _binding?.emptyLayout?.visibility = View.VISIBLE
                return
            }
            _binding?.recyclerView?.visibility = View.VISIBLE
            _binding?.emptyLayout?.visibility = View.GONE

            repayAdapter?.data = it
        }
    }

    override fun hideMullaLoading() {
        super.hideMullaLoading()
        _binding?.refreshLayout?.finishRefresh()
    }

    override fun onMullaEvent(event: MullaEventData) {
        super.onMullaEvent(event)
        when(event.eventType){
            MullaEventData.TYPE.MULLA_PRODUCT_REFRESHED -> {//刷新产品列表
                presenter.loadMullaRepayListAction()
            }
            MullaEventData.TYPE.MULLA_PRODUCT_FINISHED -> {
                hideMullaLoading()
            }
            else -> {

            }
        }
    }

    /**
     * 是否是新用户
     */
    private fun isNewUser(): Boolean{
        val dataString = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_PROCESS)
        if (dataString.isEmpty()){
            return true
        }
        val obj = JSONObject(dataString)
        if (!obj.has("userType")){
            return true
        }
        return obj.optString("userType") == "NEW"
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LOAN_REPAY_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}